/* 
 * Thx to By Cuno Pfister, @Publisher: O'Reilly Media
 * for good eksamples at  http://www.gsiot.info/download/gsiot-pachubeclient/
 * 
 */

using System;
using System.IO;
using System.Net;
using System.Text;
using Microsoft.SPOT;

namespace DaaseVarmer.helperClasses.networkComponents
{
    public class PachubeClient
    {
        const string baseUri = "http://api.pachube.com/v2/feeds/";

        public void Send(string apiKey, string feedId, string sample)
        {
            Debug.Print("time: " + DateTime.Now);
            Debug.Print("memory available: " + Debug.GC(true));

            try
            {
                using (var request = CreateRequest(apiKey, feedId, sample))
                {
                    request.Timeout = 5000;     // 5 seconds
                    // send request and receive response
                    using (var response = (HttpWebResponse)request.GetResponse())
                    {
                        HandleResponse(response);
                    }
                }
            }
            catch (Exception e)
            {
                Debug.Print(e.ToString()); 
                throw new Exception("data not sent to pachube");     
            }
        }

        HttpWebRequest CreateRequest(string apiKey, string feedId, string sample)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(sample);
            var request = (HttpWebRequest)WebRequest.Create(baseUri + feedId + ".csv");
            try
            {
               
                Debug.Print(baseUri + feedId + ".csv");

                // request line
                request.Method = "PUT";

                // request headers
                request.ContentLength = buffer.Length;
                request.ContentType = "text/csv";
                request.Headers.Add("X-PachubeApiKey", apiKey);

                // request body
                request.Timeout = 5000;
                using (Stream stream = request.GetRequestStream())
                {
                    stream.Write(buffer, 0, buffer.Length);
                }
            }
            catch (Exception)
            {
                
              
            }

            return request;
        }

        public void HandleResponse(HttpWebResponse response)
        {
            Debug.Print("pachube Status code: " + response.StatusCode);
            Debug.Print("pachube status Describtion: " + response.StatusDescription);
        }


    }
}